"""
游戏流程控制模块 - 最终修复版
包含完整的牌局展示和错误修复
"""

import random
from card import Card
from ai import DoudizhuAI
from rules import RuleEngine

class DoudizhuGame:
    def __init__(self):
        self.deck = self._create_deck()
        self.players = []
        self.history = []
        self.bottom_cards = []
        self.landlord = -1  # 初始化地主标识

    def _create_deck(self):
        """创建完整牌组"""
        deck = []
        # 生成普通牌
        suits = ['S', 'H', 'C', 'D']  # 黑桃、红心、梅花、方块
        for suit in suits:
            for rank in Card.RANKS:
                deck.append(Card(f"{rank}-{suit}"))
        # 添加特殊牌
        deck.append(Card('BJ'))
        deck.append(Card('RJ'))
        return deck

    def _deal_cards(self):
        """发牌流程"""
        random.shuffle(self.deck)
        hands = [self.deck[i*17:(i+1)*17] for i in range(3)]
        self.bottom_cards = self.deck[51:54]  # 截取底牌
        return hands

    def _bidding_phase(self):
        """叫地主流程"""
        bids = [player.make_bid() for player in self.players]
        # 从后往前找最后一个叫地主的玩家
        for i in reversed(range(3)):
            if bids[i]:
                return i
        return 0  # 默认第一个玩家当地主

    def _print_initial_hands(self):
        """打印初始牌局"""
        print("\n=== 初始牌局 ===")
        for i, player in enumerate(self.players):
            role = "地主" if i == self.landlord else "农民"
            print(f"玩家 {i} ({role}) 手牌：")
            self._print_formatted_hand(player.hand)
        print(f"\n底牌：{self._format_cards(self.bottom_cards)}")

    def _print_formatted_hand(self, hand):
        """安全格式化打印手牌"""
        sorted_hand = sorted(hand, key=lambda x: x.value)
        grouped = {}
        for card in sorted_hand:
            # 处理特殊牌显示
            if card.suit is None:
                display_name = card.rank
            else:
                display_name = f"{card.rank}-{card.suit}"
            grouped[display_name] = grouped.get(display_name, 0) + 1
        
        # 生成显示字符串
        display = []
        for name in sorted(grouped.keys(), key=lambda x: self._get_sort_value(x)):
            count = grouped[name]
            display.append(f"{name}x{count}" if count > 1 else name)
        print(' '.join(display))

    def _get_sort_value(self, display_name):
        """获取卡牌排序权重值"""
        if display_name in ['BJ', 'RJ']:
            return Card.SPECIALS[display_name]
        rank = display_name.split('-')[0]
        return Card.VALUES[rank]

    def _format_cards(self, cards):
        """格式化卡牌显示"""
        return ' '.join([str(c) for c in cards])

    def _update_round_info(self, current_player):
        """更新回合信息"""
        print(f"\n=== 玩家 {current_player} 操作后 ===")
        for i, player in enumerate(self.players):
            status = "（已出完）" if not player.hand else ""
            print(f"玩家 {i} ({'地主' if i == self.landlord else '农民'}){status} 剩余牌：")
            if player.hand:
                self._print_formatted_hand(player.hand)
        print("="*50)

    def start_game(self):
        """游戏主流程"""
    def start_game(self):
        # 初始化玩家
        hands = self._deal_cards()
        self.players = [DoudizhuAI(i, h) for i, h in enumerate(hands)]
        
        # 设置玩家相互可见
        for ai in self.players:
            ai.players = self.players  # 传递玩家列表
        
        # 叫地主流程
        self.landlord = self._bidding_phase()
        self.players[self.landlord].role = 'landlord'  # 设置地主身份
        self.players[self.landlord].hand += self.bottom_cards
        print(f"\n玩家 {self.landlord} 成为地主并获得底牌")

        # 显示初始牌局
        self._print_initial_hands()

        # 游戏循环
        current_player = self.landlord
        last_play = None
        passer_count = 0

        while True:
            player = self.players[current_player]
            action = player.select_action(last_play)
            self.history.append((current_player, action))

            # 处理出牌逻辑
            if action:
                print(f"\n玩家 {current_player} 出牌：{self._format_cards(action)}")
                # 验证出牌合法性
                is_valid, play_type = RuleEngine.validate_play(action, last_play)
                if not is_valid:
                    raise ValueError("非法出牌！")
                
                # 更新手牌
                player.hand = [c for c in player.hand if c not in action]
                last_play = (action, play_type)
                passer_count = 0
            else:
                print(f"\n玩家 {current_player} 选择不出")
                passer_count += 1

            # 更新牌局显示
            self._update_round_info(current_player)

            # 胜负判定
            if not player.hand:
                print(f"\n游戏结束！玩家 {current_player} ({'地主' if current_player == self.landlord else '农民'}) 获胜！")
                break

            # 轮转玩家
            if passer_count >= 2:
                last_play = None
                passer_count = 0
            current_player = (current_player + 1) % 3